package com.minimalist.common.response;

import com.minimalist.common.entity.basic.enums.RespEnum;

import java.io.Serial;
import java.io.Serializable;

/**
 * 统一响应对象
 *
 * @author minimalist
 */
public class R<T> implements Serializable{

    @Serial
    private static final long serialVersionUID = 1L;

    /**
     * 状态码
     */
    private Integer code;

    /**
     * 返回消息
     */
    private String message;

    /**
     * 返回数据
     */
    private T data;

    public R() {
    }

    public R(Integer code, String message, T data) {
        this.code = code;
        this.message = message;
        this.data = data;
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public static <T> RBuilder<T> builder() {
        return new RBuilder<>();
    }

    public static class RBuilder<T> {
        private Integer code;
        private String message;
        private T data;

        public RBuilder<T> code(Integer code) {
            this.code = code;
            return this;
        }

        public RBuilder<T> message(String message) {
            this.message = message;
            return this;
        }

        public RBuilder<T> data(T data) {
            this.data = data;
            return this;
        }

        public R<T> build() {
            return new R<>(code, message, data);
        }
    }

    /**
     * 成功返回
     */
    public static <T> R<T> ok(){
        return ok(null);
    }

    /**
     * 成功返回（带数据）
     */
    public static <T> R<T> ok(T data){
        R<T> r = new R<>();
        r.setCode(RespEnum.SUCCESS.getCode());
        r.setMessage(RespEnum.SUCCESS.getDesc());
        r.setData(data);
        return r;
    }

    /**
     * 失败返回
     */
    public static <T> R<T> fail(String message){
        return fail(RespEnum.FAILED.getCode(), message);
    }

    /**
     * 失败返回（带状态码）
     */
    public static <T> R<T> fail(Integer code, String message){
        R<T> r = new R<>();
        r.setCode(code);
        r.setMessage(message);
        return r;
    }

    /**
     * 根据响应枚举返回
     */
    public static <T> R<T> result(RespEnum respEnum){
        R<T> r = new R<>();
        r.setCode(respEnum.getCode());
        r.setMessage(respEnum.getDesc());
        return r;
    }
}